# -*- coding: utf-8 -*-
# author yzs
# date 2019-02-23
#
# 拓扑排序解的个数
# Description
# 给定有向无环图中所有边，计算图的拓扑排序解的个数
# Input
# 输入第一行为用例个数，后面每一行表示一个图中的所有边，边的起点和终点用空格隔开，边之间使用逗号隔开。
# Output
# 输出拓扑排序解的个数
# Sample Input 1
# 1
# a c,b c,c d,d e,d f,e g,f g
# Sample Output 1
# 4


def dfs(x):
    if x == n:
        global num
        num += 1
        return
    for i in range(n):
        if visit[i] == 0 and to[i] == 0:
            # 点入度减1
            for j in range(n):
                if edge[i][j] == 1:
                    to[j] -= 1
            # 标记访问
            visit[i] = 1
            dfs(x + 1)
            # 还原现场
            for j in range(n):
                if edge[i][j] == 1:
                    to[j] += 1
            visit[i] = 0


num = 0
t = int(input().strip())
for i in range(t):
    data = input().strip()
    nodes = data.split(',')
    n = len(set(list(data.replace(',', ' ').split())))
    edge = [[0 for _ in range(n)] for _ in range(n)]
    to = [0 for _ in range(n)]
    visit = [0] * n
    for node in nodes:
        x, y = node.split()
        edge[ord(x) - ord('a')][ord(y) - ord('a')] = 1
        to[ord(y) - ord('a')] += 1
    dfs(0)
    print(num)
